<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary"  v-on:click="toPageOne">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="success" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;"
              @row-dblclick="handleClose">
      <el-table-column type="selection" width="100">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" >
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100"  sortable>
        <template scope="scope">
          <span style="color: #11b95c" v-if="scope.row.state===1">启用</span>
          <span style="color: #b91117" v-else-if="scope.row.state===0">禁用</span>
          <span style="color: #b99511" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120" >
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180" >
      </el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button type="warning" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>

		</el-table>

    <!--抽屉-->
    <el-drawer
        title="员工列表"
        :visible.sync="table"
        direction="rtl"
        size="50%">
      <el-table :data="gridData">
        <el-table-column prop="username" label="用户名" width="80" >
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="80" >
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="110" >
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="50" >
        </el-table-column>
        <el-table-column prop="state" label="状态" width="80"  sortable>
          <template scope="scope">
            <span style="color: #11b95c" v-if="scope.row.state===1">启用</span>
            <span style="color: #b91117" v-else-if="scope.row.state===0">禁用</span>
            <span style="color: #b98911" v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="dept.name" label="所属部门" width="80" >
        </el-table-column>
        <el-table-column prop="loginf.username" label="角色" min-width="50" >
        </el-table-column>
        <el-table-column prop="shop.name" label="店铺" min-width="100" >
        </el-table-column>
      </el-table>
    </el-drawer>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>

			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"  style="float:right;"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="0">禁用</el-radio>
            <el-radio class="radio" :label="1">启用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="负责人">
          <el-select v-model="editForm.managerId" placeholder="负责人">
            <el-option
                v-for="item in emps"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.id }}</span>
            </el-option>
          </el-select>
				</el-form-item>

				<el-form-item label="上级部门">
            <el-cascader
                v-model="editForm.parentId"
                :options="options"
                :props="{ checkStrictly: true ,
                label:'name',
                value:'id'
                 }"
                clearable></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="warning" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>

	export default {
		data() {
			return {
        table: false,//默认关闭抽屉
        gridData:[],

			  // 标题
        title:'',
			  //关键字（模糊查询）
				filters: {
          keyword: ''
				},
        options:[],
        emps: [],
        value: '',
				departments: [],//部门数据
				total: 0,//总条数
        currentPage: 1,
        pageSize: 5,
				listLoading: false,
        //声明一个变量装选中的对象的集合
        sels:[],
				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

				editFormRules: {
          name: [
            {required: true, message: '请输入部门名称', trigger: 'blur'}
          ],
          sn: [
            {required: true, message: '请输入编号', trigger: 'blur'}
          ],
				},
				//编辑界面数据
				editForm: {
					id: null,
          sn:'',
          name:'',
          state:0,
          managerId:null,
          parentId:null,
				},
			}
		},
		methods: {

		  //抽屉
      handleClose(row) {
        this.table= true,//开启抽屉
          this.$http.get("/dept/findEmpByDeptId/"+row.id).then(result=>{
            console.log("测试点击当前行对象的id类型="+row.id)
            this.gridData=result.data
            console.log("后端返回的数据"+this.gridData);
          }).catch(result=>{
            this.$message({
              message: '网络不通！',
              type: 'error'
            });
          })
      },
		  //模糊查询
      toPageOne(){
        this.currentPage=1;
        this.getDepartments();
      },

			//当前页也改变
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},

			//获取部门列表
			getDepartments() {
        // 忙等开启
        this.listLoading = true;
				let para = {
          currentPage:this.currentPage,
          pageSize:this.pageSize,
          keyword:this.filters.keyword
        }
        this.$http.post("/dept/",para)
            .then(result=>{

              this.departments=result.data.rows;
              console.log("后端数据"+result.data);
              console.log("部门数据"+this.departments);
              this.total=result.data.totals;
              console.log("部门条数"+this.total)
              // 忙等关闭
              this.listLoading = false;
        })
            .catch(result=>{
          this.$message({
            message: '网络不通！',
            type: 'error'
          });
        })
			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//发送请求，并且携带参数id
          // debugger//断点
					this.$http.delete("/dept/" + row.id).
            then(result=>{
              //关闭忙等
              this.listLoading = false;
              if(result.data.success){
                this.$message({
                  message: '删除成功！',
                  type: 'success'
                });
              }
            this.currentPage=1;
            this.getDepartments();
            }).catch(result=>{
                this.$message({
                  message: '操作失败！',
                  type: 'error'
                });
            })

        });
			},

			//显示编辑界面
			handleEdit: function (index, row) {
        this.title="编辑"
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},

			//显示新增界面
			handleAdd: function () {
        this.title="新增"
        this.editFormVisible = true;
				this.editForm = {
				  id:null,
          sn:'',
          name:'',
          state:0,
          managerId:null,
          parentId:null,
				};
			},

			//编辑(新增)
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;//按钮忙等开启
              this.editFormVisible = false;//关闭模态框
      //==============================================================
							let para = Object.assign({},this.editForm);//如果编辑/新增封装的para对象中，他的parent_id存在并且是一个数组，我们才取最后一个
							if (para.parentId && para.parentId instanceof Array){
                para.parentId = para.parentId[para.parentId.length - 1]
              }
      //==============================================================
							//发送请求
							this.$http.put("/dept",para).then(result=>{
                this.editLoading = false;//按钮忙等关闭
                if (result.data.success){ //如果添加
                  this.$message({
                    message: result.data.msg,
                    type: 'success'
                  })
                }else {
                  this.$message({
                    message: result.data.msg,
                    type: 'error'
                  })
                }
                this.currentPage=1;
                this.getDepartments();
              }).catch(result=>{
                this.$message({
                  message: '网络不通！',
                  type: 'error'
                })

              })
						});
					}
				});
			},

      //将选中的对象都存放在sels数组集合中去
			selsChange: function (sels) {
				this.sels = sels;
			},

			//批量删除
			batchRemove: function () {
        //声明一个变量装获取到的所有对象id，这里涉及到stream流
        //所有对象转map，然会遍历，并获取其每个对象想的id，因为integer类型数以不需要调用toString()方法
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          //发送请求，并且携带参数id
          // aioxs异步请求+请求方式(路径 + 参数)/(路径,对象)
          this.$http.patch("/dept/" ,ids).
          then(result=>{
            //关闭忙等
            this.listLoading = false;
            if(result.data.success){
              this.$message({
                message: '删除成功！',
                type: 'success'
              });
            }
            this.currentPage=1;
            this.getDepartments();
          }).catch(result=>{
            this.$message({
              message: '操作失败！',
              type: 'error'
            });
          })

				})
			},

			//获取员工数据
      getEmployee(){
        this.$http.get("/emp")
            .then(result=>{
              this.emps=result.data;
            }).catch(result=>{
              this.$message({
                message: '网络不通！',
                type: 'error'
              });
            })
      },
      //部门树（极限树）
      getTree(){
        this.$http.get("/dept/tree")
            .then(result=>{
              this.options=result.data;
        }).catch(result=>{
          this.$message({
            message: '网络不通！',
            type: 'error'
          });
        })
      }

		},
		mounted() {
			this.getDepartments();
			this.getEmployee();
			this.getTree();
		}
	}

</script>

<style scoped>

</style>